<template>
  <div>
    <el-dialog
      title="用户注册"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <span>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="70px"
          class="demo-ruleForm"
          label-position="left"
        >
          <el-form-item label="头像" prop="avatar">
            <el-upload
              class="avatar-uploader"
              :action="upLoadAdress"
              :show-file-list="false"
              :data="upImage"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="昵称" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="ruleForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="16">
              <el-form-item label="图形码" prop="code">
                <el-input v-model="ruleForm.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <img
                :src="codeImg"
                @click="changCodeImg"
                alt=""
                style="height:40px;margin-left:20px"
              />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="验证码" prop="rcode">
                <el-input v-model="ruleForm.rcode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-button style="margin-left:20px" @click="getRcode"
                >获取短信验证码</el-button
              >
            </el-col>
          </el-row>
        </el-form></span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="register">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      dialogVisible: false,
      codeImg: process.env.VUE_APP_BASURL + '/captcha?type=sendsms',
      upLoadAdress: process.env.VUE_APP_BASURL + '/uploads',
      imageUrl: '',
      upImage: {
        image: null
      },
      ruleForm: {
        username: '',
        phone: '',
        password: '',
        email: '',
        code: '',
        rcode: '',
        avatar: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入注册昵称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入注册密码', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入注册邮箱'))
              }
              if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
                return callback(new Error('邮箱不合法'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入手机号码'))
              }
              if (!/^1[3456789][0-9]{9}$/.test(value)) {
                return callback(new Error('手机号码不合法'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '图形码不能为空', trigger: 'blur' },
          { min: 4, max: 4, message: '请真确输入图形码', trigger: 'blur' }
        ],
        rcode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
          // { min: 4, max: 4, message: '请真确输入图形码', trigger: 'blur' }
        ],
        avatar:[{required: true}]
      }
    }
  },
  watch:{
    dialogVisible(){
      if (!this.dialogVisible) {
        this.$refs.ruleForm.resetFields()
        this.imageUrl=''
        clearFiles()
      }
    }
  },
  methods: {
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    changCodeImg () {
      this.codeImg =
        process.env.VUE_APP_BASURL + `/captcha?type=sendsms&t=${new Date() - 0}`
    },
    getRcode () {
      let count = 0
      this.$refs.ruleForm.validateField(['phone', 'code'], async callback => {
        if (!callback) {
          count++
        }
        if (count == 2) {
          const res = await this.$axios.post('/sendsms', {
            phone: this.ruleForm.phone,
            code: this.ruleForm.code
          })
          if (res.code != 200) {
            this.$message({
              message: res.message,
              type: 'error',
              duration: 1000
            })
            this.changCodeImg()
          } else {
            this.ruleForm.rcode = res.data.captcha
          }
        }
      })
    },
    handleAvatarSuccess (res, file) {
      // console.log(res);
      if (res.code == 200) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.ruleForm.avatar = res.data.file_path
      } else {
        this.$message({
          message: message,
          type: 'error',
          duration: 1000
        })
      }
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.upImage.image = file
      return isJPG && isLt2M
    },
    register () {
      this.$refs.ruleForm.validate(async (valid, obj1) => {
        if (!valid) {
          return
        }
        const res = await this.$axios.post('/register', this.ruleForm)
        if (res.code == 200) {
          this.$message.success('恭喜，注册成功！')
          this.dialogVisible = false
          
        } else {
          this.$message({
            message: res.message,
            type: 'error',
            duration: 1000
          })
        }
      })
    }
  }
}
</script>

<style lang="less">
.el-dialog__footer {
  text-align: center !important;
}
.avatar-uploader {
  text-align: center;
  transform: translate(-35px);
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
